#!/usr/bin/env python
# -*- encoding: utf-8 -*-

__Author__ = "Haelwenn Monnier (lanodan) <haelwenn.monnier@gmail.com>"
__License__ = "CC-BY-SA"

import socket, sys, re, time, urllib

tetris=0
urlRegex = re.compile('[hf]t+ps?://')

def get_element(dataInput, elem):
	idx1=dataInput.find('<'+elem+'>')
	idx2=dataInput.find('</'+elem+'>')
	return dataInput[idx1+len('<'+elem+'>'):idx2].strip()

# Output to the channel and console
def printIrc(ircout):
	time.sleep(0.5)
	irc.send('PRIVMSG '+conf.channel+' :'+ircout+'\x0d\x0a')
	print 'PRIVMSG '+conf.channel+' :'+ircout

#line: append to the log (output it to the console too)
def log(line):
	print '[LOG]'+line
	log = open('IRCBot.log', 'a')
	log.write(line+'\n')
	log.close()

# Load the config file (config.py)
try:
	import conf
except Exception, e:
	print 'Exception: '+str(e)
	print 'Exiting…'
	sys.exit(1)

irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.connect((conf.server, conf.port))
#if SSLEnabled:
#	irc = ssl.wrap_socket(irc)
#
irc.send('PASS '+conf.passwd+'\x0d\x0a')
print 'PASS '+conf.passwd
irc.send('NICK '+conf.nick+'\x0d\x0a')
print 'NICK '+conf.nick
irc.send('USER '+conf.nick+' irc bot :Bot made by lanodan using python!\x0d\x0a') #user authentication
print 'USER '+conf.nick+' irc bot :Bot made by lanodan using python!'

#while 1:
#	if irc.recv(2048).find('372') != -1:
irc.send('JOIN '+conf.channel+'\x0d\x0a')
print 'JOIN '+conf.channel
#		break

time.sleep(1.5) # Random wait time, feel free to adjust it
#while 1:
#	if irc.recv(2048).find('JOIN '+channel) != -1:
printIrc(conf.welcomeMsg)
#		break

# Make a while loop to alway parse input
while 1:
	data=irc.recv(2048) # text is the socket input (I use text because input is already taken)
	text=data.lower() # text is the socket input (I use text because input is already taken)
	print data # print the input for debugging purpose

	# Below is a bunch of conditions to see if something the bot can deal with is found

	if text.find('ping :', 0, 7) != -1: 
		host = data.split('PING :', 1)[1].strip()
		irc.send('PONG '+conf.nick+' '+host+'\x0d\x0a') # Return PONG back (sort of "I'm alive")
		print 'PONG '+host+'\x0d\x0a'
	if text.find(':!hi') !=-1:
		printIrc(data.split(':!hi')[1].strip()+' '+conf.welcomeMsg) # split the message received at the :!hi part
	if text.find(':!say') != -1:
		printIrc(data.split(':!say')[1].strip())
	if text.find(':!action') != -1:
		action = data.split(':!action')[1].strip()
		printIrc('\x01ACTION '+action+'\x01') # equivalent of /me
	if urlRegex.search(text) is not None: # Use httpRegex on input
		parse = re.findall('[HhFf][Tt]{1,2}[Pp][Ss]?://[^\{\}\|\\\^\~\[\]\"\'\`\(\)\<\>\ ]+', data) # parse URL
		try:
			url = str(parse[0]).rstrip() # Take the parsed link
			if (len(url) > 8) : # I assume a link is more than 8 characters long
				try:
					get = urllib.urlopen(url) # Open the link
					wget = get.read() # Read the input of the url
					print get.info() # Print Headers
					mimeType = get.info().type # Get the Content-Type
					get.close() # Close the connection
					# find the title
					if wget.find('<title>') != -1:
						title = get_element(wget, 'title')
						printIrc('Title: '+title)
						log(url+'; '+str(mimeType)+'; '+title)
					elif wget.find('<TITLE>') != -1:
						title = get_element(wget, 'TITLE')
						printIrc('Title: '+title)
						log(url+'; '+str(mimeType)+'; '+title)
					#If we can't find the title print the Content-Type
					else:
						printIrc('Content-Type: '+mimeType)
						log(url+'; '+str(mimeType))
				except Exception, e:
					printIrc('Exception: '+str(e))
			else:
				printIrc('Link too short (not more than 8)')
		except Exception, e:
			printIrc('Exception: '+str(e))
	# Output the link to find the source code
	if text.find(':!source') != -1:
		printIrc(conf.source)
	if text.find('kick '+conf.channel+' '+conf.nick) != -1:
		time.sleep(5)
		irc.send('JOIN '+conf.channel+'\x0d\x0a') #re-join the chan
		printIrc(welcomeMsg) # Say hello
	if data[0] == ':': # Commands that do not come directly from the server
		if text.find('join') != -1:
			username = data[1:].split('!')[0]
			if username == 'fuyuneko' or username == 'lanodan':
				printIrc(username+' : Okaeri-nasai ouji-sama')
			else:
				printIrc(username+': '+conf.welcomeMsg)
	if text.find('tetris') != -1 and tetris == 0:
		printIrc('Never gonna give you up.')
		printIrc('Never gonna let you down.')
		printIrc('Never gonna run around and desert you.')
		printIrc('Never gonna make you cry.')
		printIrc('Never gonna say goodbye.')
		printIrc('Never gonna tell a lie and hurt you.')
		tetris=1 # Prevent another rick roll
	if text.find(':!nsidentify') != -1:
		irc.send('NS identify '+conf.passwd+'\x0d\x0a')
	if text.find(':!msgidentify') != -1:
		irc.send('PRIVMSG '+conf.NickServ+' :identify '+conf.passwd+'\x0d\x0a')
	if text.find(':!stop in the name of sey') != -1:
		irc.send('QUIT :'+conf.quitMsg+'\x0d\x0a')
		time.sleep(1)
		break # break the loop
	if text == "":
		irc.send('QUIT :Empty socket input\x0d\x0a')
		time.sleep(1)
		break # break the loop
irc.close() # Close the socket
sys.exit() # Exit
